package redis

import (
	"errors"
	"github.com/go-redis/redis"
	"math"
	"strings"
	"time"
)

const (
	oneWeekInSeconds = 7 * 24 * 3600
	scorePerVote     = 432
)

func PostVote(pid string, uid string, direction float64) (err error) {

	pt := client.ZScore(KeyPostTimeZSet, pid).Val()
	if float64(time.Now().Unix())-pt > oneWeekInSeconds {
		return errors.New("已超过投票时间")
	}

	key := strings.Join([]string{KeyPostVotedPX, pid}, "")
	ov := client.ZScore(key, uid).Val()
	if direction == ov {
		return errors.New("请勿重复投票")
	}
	var op float64 = -1
	if direction > ov {
		op = 1
	}
	diff := math.Abs(ov - direction)

	if _, err = client.ZIncrBy(KeyPostScoreZSet, op*diff*scorePerVote, pid).Result(); err != nil {
		return
	}

	pipeline := client.TxPipeline()

	if direction == 0 {
		_, err = pipeline.ZRem(key, uid).Result()
	} else {
		_, err = pipeline.ZAdd(key, redis.Z{
			Score:  direction,
			Member: uid,
		}).Result()
	}

	_, err = pipeline.Exec()
	return err
}
